import { defineStore } from 'pinia'
import { ElMessage } from 'element-plus'
import { login, logout, getUserInfo, refreshToken } from '@/api/auth'
import { getToken, setToken, removeToken, parseToken, isTokenExpired } from '@/utils/auth'
import router from '@/router'

export const useUserStore = defineStore('user', {
  state: () => ({
    // 用户信息
    userInfo: null,
    // 登录状态
    isLoggedIn: false,
    // 权限列表
    permissions: [],
    // 角色列表
    roles: [],
    // 学习进度
    studyProgress: {},
    // 用户偏好设置
    preferences: {
      theme: 'light',
      language: 'zh-CN',
      autoSave: true,
      notifications: true,
      soundEnabled: true
    },
    // 最近访问的课程
    recentCourses: [],
    // 收藏的内容
    favorites: {
      courses: [],
      exams: [],
      practices: []
    }
  }),

  getters: {
    // 用户头像
    avatar: (state) => {
      return state.userInfo?.avatar || '/default-avatar.png'
    },
    
    // 用户姓名
    userName: (state) => {
      return state.userInfo?.name || state.userInfo?.username || '学生'
    },
    
    // 用户学号
    studentId: (state) => {
      return state.userInfo?.studentId || ''
    },
    
    // 用户班级
    className: (state) => {
      return state.userInfo?.className || ''
    },
    
    // 用户年级
    grade: (state) => {
      return state.userInfo?.grade || ''
    },
    
    // 是否有特定权限
    hasPermission: (state) => {
      return (permission) => {
        if (!permission) return true
        return state.permissions.includes(permission)
      }
    },
    
    // 是否有特定角色
    hasRole: (state) => {
      return (role) => {
        if (!role) return true
        return state.roles.includes(role)
      }
    },
    
    // 学习统计
    studyStats: (state) => {
      const progress = state.studyProgress
      return {
        totalCourses: progress.totalCourses || 0,
        completedCourses: progress.completedCourses || 0,
        totalExams: progress.totalExams || 0,
        passedExams: progress.passedExams || 0,
        studyHours: progress.studyHours || 0,
        averageScore: progress.averageScore || 0
      }
    },
    
    // 完成率
    completionRate: (state) => {
      const stats = state.studyStats
      if (stats.totalCourses === 0) return 0
      return Math.round((stats.completedCourses / stats.totalCourses) * 100)
    },
    
    // 通过率
    passRate: (state) => {
      const stats = state.studyStats
      if (stats.totalExams === 0) return 0
      return Math.round((stats.passedExams / stats.totalExams) * 100)
    }
  },

  actions: {
    // 登录
    async login(loginForm) {
      try {
        const response = await login(loginForm)
        
        if (response.success) {
          const { token, userInfo } = response.data
          
          // 保存token
          setToken(token)
          
          // 保存用户信息
          this.userInfo = userInfo
          this.isLoggedIn = true
          this.permissions = userInfo.permissions || []
          this.roles = userInfo.roles || []
          
          // 获取学习进度
          await this.getStudyProgress()
          
          // 获取用户偏好
          await this.getUserPreferences()
          
          return { success: true }
        } else {
          return { success: false, message: response.message }
        }
      } catch (error) {
        console.error('登录失败:', error)
        return { success: false, message: error.message || '登录失败' }
      }
    },

    // 退出登录
    async logout() {
      try {
        await logout()
      } catch (error) {
        console.error('退出登录失败:', error)
      } finally {
        // 清除本地数据
        this.clearUserData()
        
        // 跳转到登录页
        router.push('/login')
      }
    },

    // 获取用户信息
    async getUserInfo() {
      try {
        const response = await getUserInfo()
        
        if (response.success) {
          this.userInfo = response.data
          this.isLoggedIn = true
          this.permissions = response.data.permissions || []
          this.roles = response.data.roles || []
          
          return response.data
        } else {
          throw new Error(response.message)
        }
      } catch (error) {
        console.error('获取用户信息失败:', error)
        throw error
      }
    },

    // 刷新token
    async refreshUserToken() {
      try {
        const response = await refreshToken()
        
        if (response.success) {
          setToken(response.data.token)
          return true
        } else {
          throw new Error(response.message)
        }
      } catch (error) {
        console.error('刷新token失败:', error)
        await this.logout()
        return false
      }
    },

    // 检查登录状态
    async checkLoginStatus() {
      const token = getToken()
      
      if (!token) {
        this.clearUserData()
        return false
      }
      
      // 检查token是否过期
      if (isTokenExpired(token)) {
        // 尝试刷新token
        const refreshed = await this.refreshUserToken()
        if (!refreshed) {
          return false
        }
      }
      
      // 获取用户信息
      if (!this.userInfo) {
        try {
          await this.getUserInfo()
        } catch (error) {
          this.clearUserData()
          return false
        }
      }
      
      return true
    },

    // 检查权限
    async checkPermission(permission) {
      if (!permission) return true
      
      // 确保用户信息已加载
      if (!this.userInfo) {
        await this.getUserInfo()
      }
      
      return this.hasPermission(permission)
    },

    // 获取学习进度
    async getStudyProgress() {
      try {
        // 这里调用API获取学习进度
        // const response = await api.getStudyProgress()
        // this.studyProgress = response.data
        
        // 模拟数据
        this.studyProgress = {
          totalCourses: 12,
          completedCourses: 8,
          totalExams: 15,
          passedExams: 12,
          studyHours: 156,
          averageScore: 85.6
        }
      } catch (error) {
        console.error('获取学习进度失败:', error)
      }
    },

    // 获取用户偏好设置
    async getUserPreferences() {
      try {
        // 从本地存储获取偏好设置
        const savedPreferences = localStorage.getItem('userPreferences')
        if (savedPreferences) {
          this.preferences = { ...this.preferences, ...JSON.parse(savedPreferences) }
        }
        
        // 这里也可以从服务器获取
        // const response = await api.getUserPreferences()
        // this.preferences = { ...this.preferences, ...response.data }
      } catch (error) {
        console.error('获取用户偏好失败:', error)
      }
    },

    // 更新用户偏好设置
    async updatePreferences(newPreferences) {
      try {
        this.preferences = { ...this.preferences, ...newPreferences }
        
        // 保存到本地存储
        localStorage.setItem('userPreferences', JSON.stringify(this.preferences))
        
        // 同步到服务器
        // await api.updateUserPreferences(this.preferences)
        
        ElMessage.success('设置已保存')
      } catch (error) {
        console.error('更新用户偏好失败:', error)
        ElMessage.error('保存设置失败')
      }
    },

    // 添加最近访问的课程
    addRecentCourse(course) {
      const existingIndex = this.recentCourses.findIndex(c => c.id === course.id)
      
      if (existingIndex > -1) {
        // 如果已存在，移到最前面
        this.recentCourses.splice(existingIndex, 1)
      }
      
      this.recentCourses.unshift({
        ...course,
        visitTime: new Date().toISOString()
      })
      
      // 只保留最近10个
      if (this.recentCourses.length > 10) {
        this.recentCourses = this.recentCourses.slice(0, 10)
      }
      
      // 保存到本地存储
      localStorage.setItem('recentCourses', JSON.stringify(this.recentCourses))
    },

    // 添加收藏
    async addFavorite(type, item) {
      try {
        if (!this.favorites[type]) {
          this.favorites[type] = []
        }
        
        const exists = this.favorites[type].some(fav => fav.id === item.id)
        if (!exists) {
          this.favorites[type].push({
            ...item,
            favoriteTime: new Date().toISOString()
          })
          
          // 同步到服务器
          // await api.addFavorite(type, item.id)
          
          ElMessage.success('已添加到收藏')
        } else {
          ElMessage.info('已经收藏过了')
        }
      } catch (error) {
        console.error('添加收藏失败:', error)
        ElMessage.error('收藏失败')
      }
    },

    // 移除收藏
    async removeFavorite(type, itemId) {
      try {
        if (this.favorites[type]) {
          this.favorites[type] = this.favorites[type].filter(fav => fav.id !== itemId)
          
          // 同步到服务器
          // await api.removeFavorite(type, itemId)
          
          ElMessage.success('已取消收藏')
        }
      } catch (error) {
        console.error('取消收藏失败:', error)
        ElMessage.error('取消收藏失败')
      }
    },

    // 清除用户数据
    clearUserData() {
      this.userInfo = null
      this.isLoggedIn = false
      this.permissions = []
      this.roles = []
      this.studyProgress = {}
      this.recentCourses = []
      this.favorites = {
        courses: [],
        exams: [],
        practices: []
      }
      
      // 清除token
      removeToken()
      
      // 清除本地存储的数据
      localStorage.removeItem('recentCourses')
      localStorage.removeItem('userPreferences')
    },

    // 更新用户信息
    updateUserInfo(userInfo) {
      this.userInfo = { ...this.userInfo, ...userInfo }
    },

    // 更新学习进度
    updateStudyProgress(progress) {
      this.studyProgress = { ...this.studyProgress, ...progress }
    }
  },

  // 持久化配置
  persist: {
    key: 'student-user-store',
    storage: localStorage,
    paths: ['userInfo', 'preferences', 'recentCourses', 'favorites']
  }
})